﻿using System;
using System.Collections.Generic;
using MediaPortal.Dialogs;
using MediaPortal.GUI.Library;
using Action = MediaPortal.GUI.Library.Action;
using System.Windows.Forms;
using System.Reflection;


namespace FlashGames.MediaPortal1
{
  public class FlashGamesGUI : GUIWindow, ISetupForm
  {
    public static FlashUnityPlayer.Player player = null;
    public FlashGames flashgames = new FlashGames();
    public Object SelectedItem;
    public int SelectedItemIndex = 0;

    [SkinControlAttribute(2)]
    protected GUIButtonControl buttonOne = null;
    [SkinControlAttribute(3)]
    protected GUIButtonControl buttonTwo = null;
    [SkinControlAttribute(4)]
    protected GUIButtonControl buttonThree = null;
    [SkinControlAttribute(50)]
    protected GUIListControl ListControl = null;
    [SkinControlAttribute(1000)]
    protected GUIImage PlayerWindow = null;

    public FlashGamesGUI()
    {

    }

    #region ISetupForm Members

    // Returns the name of the plugin which is shown in the plugin menu
    public string PluginName()
    {
      return "Flash Games";
    }

    // Returns the description of the plugin is shown in the plugin menu
    public string Description()
    {
      return "Play Flash Games Inside Mediaportal";
    }

    // Returns the author of the plugin which is shown in the plugin menu
    public string Author()
    {
      return "Quarter";
    }

    // show the setup dialog
    public void ShowPlugin()
    {
      Configuration config = new Configuration();
      config.ShowDialog();
    }

    // Indicates whether plugin can be enabled/disabled
    public bool CanEnable()
    {
      return true;
    }

    // Get Windows-ID
    public int GetWindowId()
    {
      // WindowID of windowplugin belonging to this setup
      // enter your own unique code
      return 8796;
    }

    // Indicates if plugin is enabled by default;
    public bool DefaultEnabled()
    {
      return true;
    }

    // indicates if a plugin has it's own setup screen
    public bool HasSetup()
    {
      return true;
    }

    /// <summary>
    /// If the plugin should have it's own button on the main menu of Mediaportal then it
    /// should return true to this method, otherwise if it should not be on home
    /// it should return false
    /// </summary>
    /// <param name="strButtonText">text the button should have</param>
    /// <param name="strButtonImage">image for the button, or empty for default</param>
    /// <param name="strButtonImageFocus">image for the button, or empty for default</param>
    /// <param name="strPictureImage">subpicture for the button or empty for none</param>
    /// <returns>true : plugin needs it's own button on home
    /// false : plugin does not need it's own button on home</returns>

    public bool GetHome(out string strButtonText, out string strButtonImage,
      out string strButtonImageFocus, out string strPictureImage)
    {
      strButtonText = PluginName();
      strButtonImage = String.Empty;
      strButtonImageFocus = String.Empty;
      strPictureImage = String.Empty;
      return true;
    }

    // With GetID it will be an window-plugin / otherwise a process-plugin
    // Enter the id number here again
    public override int GetID
    {
      get
      {
        return 8796;
      }

      set
      {
      }
    }

    #endregion

    public override bool Init()
    {
      return Load(GUIGraphicsContext.Skin + @"\FlashGames.xml");
    }

    protected override void OnPageLoad()
    {
      try
      {
        GUIPropertyManager.SetProperty("#FlashGames.Name", PluginName());
        GUIWaitCursor.Show();
        List<Site> ListItems = flashgames.GetSiteList();
        foreach (Site site in ListItems)
        {
          ListControl.ListItems.Add(site.ToGUIListItem());
        }
        GUIPropertyManager.SetProperty("#FlashGames.ListItemsCount", ListControl.ListItems.Count.ToString());
        base.OnPageLoad();
      }
      catch
      {
        GUIWaitCursor.Hide();
      }
      GUIWaitCursor.Hide();
    }

    public override void DeInit()
    {
      if (player != null)
        player.Dispose();
      base.DeInit();
    }

    protected override void OnClicked(int controlId, GUIControl control,
      MediaPortal.GUI.Library.Action.ActionType actionType)
    {
      if (control == buttonOne)
        OnButtonOne();
      if (control == buttonTwo)
        OnButtonTwo();
      if (control == buttonThree)
        OnButtonThree();
      if (control == ListControl)
        OnListControl();
      base.OnClicked(controlId, control, actionType);
    }

    private void OnButtonOne()
    {
      player.PlayerWindow = FlashUnityPlayer.Player.FlashUnityWindow.Fullscreen;
      Log.Debug("GamePlayer Window FullScreen");
    }

    private void OnButtonTwo()
    {
      DoBackStep();
    }

    private void OnButtonThree()
    {
      if (flashgames.GetMyGames() != null)
      {
        ListControl.ListItems.Clear();
        foreach (Game game in flashgames.GetMyGames())
        {
          ListControl.ListItems.Add(game.ToGUIListItem());
        }
      }
    }

    private void OnListControl()
    {
      SelectedItem = ListControl.SelectedListItem.AlbumInfoTag;
      GetNextMenuItem(SelectedItem);
      GUIPropertyManager.SetProperty("#FlashGames.ListItemsCount", ListControl.ListItems.Count.ToString());
      GUIPropertyManager.SetProperty("#FlashGames.SelectedItem", ListControl.SelectedListItem.Label);
    }

    public void GetNextMenuItem(Object Item)
    {
      if (Item.GetType() == typeof(Site))
      {
        ListControl.ListItems.Clear();
        foreach (Object obj in flashgames.GetNext(Item))
        {
          if (obj.GetType() == typeof(Category))
          {
            Category category = (Category)obj;
            ListControl.ListItems.Add(category.ToGUIListItem());
          }
          else if (obj.GetType() == typeof(Game))
          {
            Game game = (Game)obj;
            ListControl.ListItems.Add(game.ToGUIListItem());
          }
        }
      }
      else if (Item.GetType() == typeof(Category))
      {
        ListControl.ListItems.Clear();
        foreach (Object obj in flashgames.GetNext(Item))
        {
          if (obj.GetType() == typeof(Category))
          {
            Category category = (Category)obj;
            ListControl.ListItems.Add(category.ToGUIListItem());
          }

          else
          {
            Game game = (Game)obj;
            ListControl.ListItems.Add(game.ToGUIListItem());
          }
        }
      }

      else if (Item.GetType() == typeof(Game))
      {
        Game game = (Game)Item;
        if (string.IsNullOrEmpty(game.FileUrl))
        {
          game.LoadGame();
          string b = game.FileUrl;
        }
        PlayerPlay(game.FileUrl);
      }

      ListControl.SelectedListItemIndex = 0;
    }

    public bool GetLastMenuItem()
    {

      ListControl.ListItems.Clear();

      if (SelectedItem == null)
      {
        return false;
      }
      else if (SelectedItem.GetType() == typeof(Site))
      {
        foreach (Object Item in flashgames.GetLast(ref SelectedItem))
        {
          Site site = (Site)Item;
          ListControl.ListItems.Add(site.ToGUIListItem());
        }
      }
      else if (SelectedItem.GetType() == typeof(Category))
      {
        foreach (Object Item in flashgames.GetLast(ref SelectedItem))
        {
          Category category = (Category)Item;
          ListControl.ListItems.Add(category.ToGUIListItem());
        }
      }
      else if (SelectedItem.GetType() == typeof(Game))
      {
        foreach (Object Item in flashgames.GetLast(ref SelectedItem))
        {
          if (Item.GetType() == typeof(Category))
          {
            Category category = (Category)Item;
            ListControl.ListItems.Add(category.ToGUIListItem());
          }
          else if (Item.GetType() == typeof(Site))
          {
            Site site = (Site)Item;
            ListControl.ListItems.Add(site.ToGUIListItem());
          }
        }
      }
      return true;
    }

    public void PlayerPlay(string Url)
    {
      if (string.IsNullOrEmpty(Url))
      {
        GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
        dlg.SetHeading("Unable to load game");
        dlg.SetText("No Url......");
        dlg.DoModal(GUIWindowManager.ActiveWindow);
        Log.Debug("No Url Returned");
        GUIWaitCursor.Hide();
      }

      else if (Url.ToLower().Contains("unity3d") || Url.ToLower().Contains("swf"))
      {
        if (player == null)
        {
          player = new FlashUnityPlayer.Player();
          player.OnRightClick += player_OnRightClick;
          player.Disposed += player_Disposed;
          player.Location = new System.Drawing.Point(PlayerWindow._positionX, PlayerWindow._positionY);
          player.Size = new System.Drawing.Size(PlayerWindow._width, PlayerWindow._height);
          GUIGraphicsContext.form.Controls.Add(player);
          player.Play(Url);

          GUIGraphicsContext.MouseSupport = true;
          FieldInfo fieldinfo = GUIGraphicsContext.form.GetType().GetField("AutoHideMouse", BindingFlags.NonPublic | BindingFlags.Instance);
          fieldinfo.SetValue(GUIGraphicsContext.form, false);
          Log.Debug("AutoHideMouse Disabled");
          ListControl.Disabled = true;

        }
      }

      else
      {
        GUIDialogNotify dlg = (GUIDialogNotify)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_NOTIFY);
        dlg.SetHeading("Unable to load game");
        dlg.SetText("Unknown File Type......");
        dlg.DoModal(GUIWindowManager.ActiveWindow);
        Log.Debug("Unknown File : " + Url);
      }
    }

    public void DoBackStep()
    {
      int i = ListControl.SelectedListItemIndex;
      if (player != null)
      {
        if (player.PlayerWindow == FlashUnityPlayer.Player.FlashUnityWindow.Fullscreen)
          player.PlayerWindow = FlashUnityPlayer.Player.FlashUnityWindow.Normal;
        else player.Dispose();
      }
      else if (GetLastMenuItem()) { ListControl.SelectedListItemIndex = i; }
      else this.OnPreviousWindow();
    }

    private void player_OnRightClick(object sender, EventArgs e)
    {
      if (player != null)
        DoBackStep();
    }

    private void player_Disposed(object sender, EventArgs e)
    {
      FieldInfo fieldinfo = GUIGraphicsContext.form.GetType().GetField("AutoHideMouse", BindingFlags.NonPublic | BindingFlags.Instance);
      fieldinfo.SetValue(GUIGraphicsContext.form, true);
      GUIGraphicsContext.MouseSupport = true;
      Cursor.Hide();
      ListControl.Focus = true;
      ListControl.Disabled = false;
      player = null;
    }

    public override void OnAction(Action action)
    {
      if (player != null && player.IsFocused)
        return;
      switch (action.wID)
      {
        case Action.ActionType.ACTION_PREVIOUS_MENU:
        case Action.ActionType.ACTION_EXIT:
          {
            DoBackStep();
            return;
          }
      }
      base.OnAction(action);
    }
  }
}